package com.et.helper

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.et.helper.databinding.ActivityMainBinding
import com.et.helper.databinding.ItemMainBinding
import com.et.util.shell
import com.shuaijun.plant.util.Adapter
import com.shuaijun.plant.util.ViewHolder
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var assetsList: MutableList<AssetsContent>
    private lateinit var adapter: Adapter<AssetsContent, ItemMainBinding>
    private lateinit var subscribe: Disposable

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(LayoutInflater.from(this))
        setContentView(binding.root)
        Thread{
            copyFromAssets()
            getExternalFilesDir("apk")?.apply {
                if (exists()) {
                    listFiles()?.apply {
                        val string = StringBuilder(1024)
                        forEach {
                            shell("pm install -r ${it.absolutePath}", string)
                        }
                        Log.d("et_log", "Shell:$string")
                    }
                }
            }
        }.start()
    }

    private fun copyFromAssets() {
        getExternalFilesDir("apk")?.apply {
            if (!exists()) mkdirs()
            if (exists()) {
                com.et.util.copyFromAssets(applicationContext, "apk", this)
            }
        }
    }

    private fun initData() {
        assetsList = mutableListOf()
        adapter = Adapter(assetsList, { v, p ->
            v.labelName.text = assetsList[p].name
        }, { parent ->
            ViewHolder(
                ItemMainBinding.inflate(
                    LayoutInflater.from(parent.context),
                    parent,
                    false
                )
            )
        })

        binding.recyclerview.layoutManager = LinearLayoutManager(this).also {
            it.orientation = LinearLayoutManager.VERTICAL
        }
        binding.recyclerview.adapter = adapter
        binding.recyclerview.addItemDecoration(DividerItemDecoration(this, RecyclerView.VERTICAL))
        subscribe = Single.just(assetsList)
            .map {
                assets.list("")?.let { a ->
                    if (a.isNotEmpty()) {
                        a.forEach { file ->
                            if (file.endsWith(".apk")) {
                                Log.d("et_log", "file = $file")
                                it.add(AssetsContent(file, ""))
                            }
                        }
                    }
                }
                return@map it
            }.map {
                if (it.isNotEmpty()) {
                    for (i in it.indices) {
                        for (j in KEY.indices) {
                            if (it[i].file.startsWith(KEY[j])) {
                                it[i].name = NAME[j]
                                break
                            }
                        }
                    }
                }
                return@map it
            }.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {
                adapter.notifyDataSetChanged()
            })
    }

    override fun onPause() {
        super.onPause()
        if (!subscribe.isDisposed) subscribe.dispose()
    }

    override fun onResume() {
        super.onResume()
        initData()
    }

    companion object {
        private val KEY = arrayOf("install", "launch", "machine", "party", "u0", "u1", "u2", "u3")
        private val NAME =
            arrayOf("安装器", "启动器", "驱动程序", "第三方支付插件", "低配4.2售卖软件", "5.1+售卖软件", "7.1+售卖软件", "暂未启用")
    }
}

data class AssetsContent(var file: String, var name: String)